#include <tron.h>
#include <defs.h>
#include <user.h>
#include <track.h>
#include <controller.h>
#include <reserver.h>
#include <random.h>
#include <utils.h>
#include <random.h>
#include <printer.h>
#include <pathplanner.h>
#include <messages.h>

int GetNext(int pos, int next) {
  track_node node;
  GetNode(next, &node);
  if (node.type == NODE_SWITCH && node.sw.behind.dest == pos) {
    int straight = SRand(Time()) % 2;
    Sw(InternalToSwitch(next), straight ? 'S' : 'C');    
    return node.sw.ahead[straight].dest;
  }
  else if (node.type == NODE_SWITCH) {
    return node.sw.behind.dest;
  }
  else if (node.type == NODE_SENSOR) {
    if (pos == node.se.ahead.dest)
      return node.se.behind.dest;
    else
      return node.se.ahead.dest;
  }
  else {
    return pos;
  }
}

void Tron() {
  
  int train, pos, next, opponent;
  tron_msg msg;  
  
  // notify parent
  int parent_tid;
  Receive(&parent_tid, (char*)&msg, sizeof(tron_msg));
  train = msg.train;
  pos = msg.pos;
  next = msg.next;
  opponent = msg.opponent;
  Reply(parent_tid, NULL, 0);
  
  ReserveTrack(pos, next);
  int afterNext = GetNext(pos, next);
  pos = next;
  next = afterNext;
  Tr(train, 6);
  
  for (;;) {
    if (ReserveTrack(pos, next)) {
      landmark_event event;
      do {
        AwaitEvent(EVENT_LANDMARK, (char*)&event, sizeof(landmark_event));
        // PrintAt(1, 24, "%d: Event train: %d; Event landmrk: %d\r\n", train, event.train, event.landmark);
      } while (event.train == train);
      afterNext = GetNext(pos, next);
      pos = next;
      next = afterNext;
      if (pos == next)
        Rv(train);
    }
    else {
      PrintAt(1, 24, "Train %d WON - Train %d LOST. Game over.\r\n", opponent, train);
      break;
    }
  }
  Tr(train, 0);
  Tr(opponent, 0);
  
  Exit();
}

void PlayGame(int train, int pos, int next, int opponent, int tron_tid) {
  tron_msg msg;
  msg.train = train;
  msg.pos = pos;
  msg.next = next;
  msg.opponent = opponent;
  Send(tron_tid, (char*)&msg, sizeof(tron_msg), NULL, 0); 
}
